package com.sdy.approval.biz.service.impl;

import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sdy.approval.biz.model.TpApproveFlowConfig;
import com.sdy.approval.biz.model.TpConfigOld;
import com.sdy.approval.biz.model.TpOrder;
import com.sdy.approval.biz.param.AddApprovalsParam;
import com.sdy.approval.biz.service.TpApproveFlowConfigService;
import com.sdy.approval.biz.service.TpConfigOldService;
import com.sdy.approval.biz.service.TpOrderService;
import com.sdy.common.model.BizException;
import com.sdy.common.utils.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sdy.approval.biz.mapper.TpApproveFlowMapper;
import com.sdy.approval.biz.model.TpApproveFlow;
import com.sdy.approval.biz.service.TpApproveFlowService;
import com.sdy.mvc.service.impl.BaseServiceImpl;

import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 审批记录 服务实现类
 * </p>
 *
 * @author cgj
 * @since 2019-08-09
 */
@Slf4j
@Service
// @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=30000,rollbackFor=Exception.class)
public class TpApproveFlowServiceImpl extends BaseServiceImpl<TpApproveFlow> implements TpApproveFlowService {
    @Autowired
    private TpApproveFlowMapper tpApproveFlowMapper;
    @Autowired
	private TpApproveFlowService tpApproveFlowService;
    @Autowired
	private TpApproveFlowConfigService tpApproveFlowConfigService;
    @Autowired
	private TpOrderService tpOrderService;
    @Autowired
	private TpConfigOldService tpConfigOldService;

	/**
	 * 撤回生成的流程
	 * @param applyNum
	 * @param date
	 * @param userId
	 * @return
	 * @throws BizException
	 */
	@Override
	public Boolean withdrawFlows(String applyNum, Date date, Integer userId) throws BizException {
		// ------------撤回TpApprovaFlow----------------------
		LambdaUpdateWrapper<TpApproveFlow> withDrawTaf = new LambdaUpdateWrapper<>();
		withDrawTaf.eq(TpApproveFlow::getApplyId, applyNum)
				.eq(TpApproveFlow::getFlowAvailable, 1)
				.set(TpApproveFlow::getFlowAvailable, 2)
				.set(TpApproveFlow::getModifyTime, date)
				.set(TpApproveFlow::getCancelUserId, userId);
		Boolean wdtaf = tpApproveFlowService.update(withDrawTaf);
		Assert.notTrue(wdtaf, "(云订单)撤回TpApproveFlow内数据失败!");
		return true;
	}

	/**
	 * 走flow_flowconfig的审批
	 * @param applyNum
	 * @param oneFlow
	 * @param date
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	@Override
	public Integer updateResultByConfig(String applyNum, TpApproveFlow oneFlow, Date date, Integer userId) throws Exception {
		String resId = oneFlow.getResId();
		int currentFlowLink = oneFlow.getCurrentFlowLink();
		// 拿到该节点的节点模板数据
		TpApproveFlowConfig tpApproveFlowConfig = tpApproveFlowConfigService.selectByResIdAndCurrentFlowLink(resId, currentFlowLink);
		// 如果没有下一节点
		if (tpApproveFlowConfig!=null&&null == tpApproveFlowConfig.getNextFlowNode()) {
			boolean updateTpOrder = tpOrderService.update(Wrappers.<TpOrder>lambdaUpdate()
					.eq(TpOrder::getApplicationNum, applyNum).eq(TpOrder::getOrderAvailable, 1)
					.set(TpOrder::getGsOrderState, 6).set(TpOrder::getOrderAvailable, 1)
					.set(TpOrder::getModifyTime, date));
			Assert.notTrue(updateTpOrder, "修改云订单状态时出错！");
			// 发送Mq
			Boolean mqBoolean = tpOrderService.sendMq(applyNum, resId);
			Assert.notTrue(mqBoolean, "mq发送消息失败！");
			log.info("updateResultByConfig-没有下一节点，审批完成！");
			return 1;
			// 如果是第一节点而且不是最后一个节点
		} else if (tpApproveFlowConfig!=null&&currentFlowLink == 1 && tpApproveFlowConfig.getNextFlowNode() != null) {
			boolean updateTpOrder = tpOrderService.update(Wrappers.<TpOrder>lambdaUpdate()
					.eq(TpOrder::getApplicationNum, applyNum).eq(TpOrder::getOrderAvailable, 1)
					.set(TpOrder::getGsOrderState, 4).set(TpOrder::getOrderAvailable, 1)
					.set(TpOrder::getModifyTime, date));
			Assert.notTrue(updateTpOrder, "修改云订单状态时出错！");
			// 发送Mq
			Boolean mqBoolean = tpOrderService.sendMq(applyNum, resId);
			Assert.notTrue(mqBoolean, "mq发送消息失败！");
			// 新增下一节点
			Boolean addNextFlow = tpApproveFlowService.addNextFlow(tpApproveFlowConfig, applyNum, date, userId);
			Assert.notTrue(addNextFlow, "新增下一节点时失败！");
			log.info("updateResultByConfig-第一节点而且不是最后一个节点，审批完成！");
			return 1;
			// 不是第一节点，也不是最后节点
		} else {
			// 新增下一节点
			Boolean addNextFlow = tpApproveFlowService.addNextFlow(tpApproveFlowConfig, applyNum, date, userId);
			Assert.notTrue(addNextFlow, "新增下一节点时失败！");
			log.info("updateResultByConfig-不是第一节点，也不是最后节点，审批完成！");
			return 1;
		}
	}



	/**
	 * 不走flow_flowconfig的审批
	 * @param applyNum
	 * @param oneFlow
	 * @param date
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	@Override
	public Integer updateResultNotByConfig(String applyNum, TpApproveFlow oneFlow, Date date, Integer userId,Integer deptBaseId,Integer roleBaseId) throws Exception {
		String resId = oneFlow.getResId();
		int currentFlowLink = oneFlow.getCurrentFlowLink();
		// 如果没有下一节点
		if (null == oneFlow.getNextFlowLink()) {
			boolean updateTpOrder = tpOrderService.update(Wrappers.<TpOrder>lambdaUpdate()
					.eq(TpOrder::getApplicationNum, applyNum).eq(TpOrder::getOrderAvailable, 1)
					.set(TpOrder::getGsOrderState, 6).set(TpOrder::getOrderAvailable, 1)
					.set(TpOrder::getModifyTime, date));
			Assert.notTrue(updateTpOrder, "修改云订单状态时出错！");
			// 发送Mq
			Boolean mqBoolean = tpOrderService.sendMq(applyNum, resId);
			Assert.notTrue(mqBoolean, "mq发送消息失败！");
			log.info("updateResultByConfig-没有下一节点，审批完成！");
			return 1;
			// 如果是第一节点而且不是最后一个节点
		} else if (currentFlowLink == 1 && oneFlow.getNextFlowLink() != null) {
			boolean updateTpOrder = tpOrderService.update(Wrappers.<TpOrder>lambdaUpdate()
					.eq(TpOrder::getApplicationNum, applyNum).eq(TpOrder::getOrderAvailable, 1)
					.set(TpOrder::getGsOrderState, 4).set(TpOrder::getOrderAvailable, 1)
					.set(TpOrder::getModifyTime, date));
			Assert.notTrue(updateTpOrder, "修改云订单状态时出错！");
			// 发送Mq
			Boolean mqBoolean = tpOrderService.sendMq(applyNum, resId);
			Assert.notTrue(mqBoolean, "mq发送消息失败！");
			// 新增下一节点
			Boolean addNextFlow = tpApproveFlowService.addNextFlowNotByConfIg(oneFlow, applyNum, date, userId,deptBaseId,roleBaseId);
			Assert.notTrue(addNextFlow, "新增下一节点时失败！");
			log.info("updateResultByConfig-第一节点而且不是最后一个节点，审批完成！");
			return 1;
			// 不是第一节点，也不是最后节点
		} else {
			// 新增下一节点
			Boolean addNextFlow = tpApproveFlowService.addNextFlowNotByConfIg(oneFlow, applyNum, date, userId,deptBaseId,roleBaseId);
			Assert.notTrue(addNextFlow, "新增下一节点时失败！");
			log.info("updateResultByConfig-不是第一节点，也不是最后节点，审批完成！");
			return 1;
		}
	}

	/**
	 * 遗留订单，下架后，该流程需要走流程配置历史的审批
	 * @param applyNum
	 * @param oneFlow
	 * @param date
	 * @param userId
	 * @param configHisNum
	 * @return
	 */
	@Override
	public Integer updateResultByOldConfig(String applyNum, TpApproveFlow oneFlow, Date date, Integer userId, Integer configHisNum) throws Exception {
		String resId = oneFlow.getResId();
		int currentFlowLink = oneFlow.getCurrentFlowLink();
		// 拿到该节点的节点模板数据
		TpConfigOld oldConfig = tpConfigOldService.getOne(Wrappers.<TpConfigOld>lambdaQuery().eq(TpConfigOld::getResId, resId)
				.eq(TpConfigOld::getCurrentFlowLink, currentFlowLink).eq(TpConfigOld::getHistoryNum, configHisNum));
		// 如果没有下一节点
		if (null == oldConfig.getNextFlowNode()) {
			boolean updateTpOrder = tpOrderService.update(Wrappers.<TpOrder>lambdaUpdate()
					.eq(TpOrder::getApplicationNum, applyNum).eq(TpOrder::getOrderAvailable, 1)
					.set(TpOrder::getGsOrderState, 6).set(TpOrder::getOrderAvailable, 1)
					.set(TpOrder::getModifyTime, date));
			Assert.notTrue(updateTpOrder, "修改云订单状态时出错！");
			// 发送Mq
			Boolean mqBoolean = tpOrderService.sendMq(applyNum, resId);
			Assert.notTrue(mqBoolean, "mq发送消息失败！");
			log.info("updateResultByConfig-没有下一节点，审批完成！");
			return 1;
			// 如果是第一节点而且不是最后一个节点
		} else if (currentFlowLink == 1 && oldConfig.getNextFlowNode() != null) {
			boolean updateTpOrder = tpOrderService.update(Wrappers.<TpOrder>lambdaUpdate()
					.eq(TpOrder::getApplicationNum, applyNum).eq(TpOrder::getOrderAvailable, 1)
					.set(TpOrder::getGsOrderState, 4).set(TpOrder::getOrderAvailable, 1)
					.set(TpOrder::getModifyTime, date));
			Assert.notTrue(updateTpOrder, "修改云订单状态时出错！");
			// 发送Mq
			Boolean mqBoolean = tpOrderService.sendMq(applyNum, resId);
			Assert.notTrue(mqBoolean, "mq发送消息失败！");
			// 新增下一节点
			Boolean addNextFlow = tpApproveFlowService.addNextOldFlow(oldConfig, applyNum, date, userId, configHisNum);
			Assert.notTrue(addNextFlow, "新增下一节点时失败！");
			log.info("updateResultByConfig-第一节点而且不是最后一个节点，审批完成！");
			return 1;
			// 不是第一节点，也不是最后节点
		} else {
			// 新增下一节点
			Boolean addNextFlow = tpApproveFlowService.addNextOldFlow(oldConfig, applyNum, date, userId, configHisNum);
			Assert.notTrue(addNextFlow, "新增下一节点时失败！");
			log.info("updateResultByConfig-不是第一节点，也不是最后节点，审批完成！");
			return 1;
		}
	}

	/**
	 * 遗留订单，审批时生成新的节点
	 * @param tpConfigOld
	 * @param applyNum
	 * @param date
	 * @param userId
	 * @return
	 * @throws BizException
	 */
	@Override
	public Boolean addNextOldFlow(TpConfigOld tpConfigOld, String applyNum, Date date, Integer userId, Integer historyNum) {
		String resId = tpConfigOld.getResId();
		String resIdRc = resId;
		if (resId.contains("[事项录入]")) {
			resId = "[事项录入]";
		}
		TpConfigOld oldConfig = tpConfigOldService.getOne(Wrappers.<TpConfigOld>lambdaQuery().eq(TpConfigOld::getResId, resId)
				.eq(tpConfigOld.getNextFlowNode() != null, TpConfigOld::getCurrentFlowLink, tpConfigOld.getNextFlowNode())
				.eq(TpConfigOld::getHistoryNum, historyNum));
		int auditDepartmentId = oldConfig.getAuditDepartmentId();
		int auditRoleId = oldConfig.getAuditRoleId();
		if (resId.contains("[事项录入]")) {
			// 新增下一节点
			TpApproveFlow tpApproveFlowRc = new TpApproveFlow();
			tpApproveFlowRc.setApplyId(applyNum).setApprovalDeptId(auditDepartmentId)
					.setApprovalRoleId(auditRoleId).setResId(resIdRc).setResult(1).setFlowAvailable(1).setConfigHisNum(historyNum)
					.setCreateTime(date).setCurrentFlowLink(tpConfigOld.getCurrentFlowLink())
					.setNextFlowLink(tpConfigOld.getNextFlowNode()).setUserId(userId);
			boolean save = tpApproveFlowService.save(tpApproveFlowRc);
			if (!save) {
				log.info("新增下一节点失败！ ");
				return false;
			}
		} else {
			// 新增下一节点
			TpApproveFlow tpApproveFlow = new TpApproveFlow();
			tpApproveFlow.setApplyId(applyNum).setApprovalDeptId(auditDepartmentId)
					.setApprovalRoleId(auditRoleId).setResId(resId).setResult(1).setFlowAvailable(1).setConfigHisNum(historyNum)
					.setCreateTime(date).setCreateTime(date).setCurrentFlowLink(tpConfigOld.getCurrentFlowLink())
					.setNextFlowLink(tpConfigOld.getNextFlowNode()).setUserId(userId);
			boolean save = tpApproveFlowService.save(tpApproveFlow);
			if (!save) {
				log.info("新增下一节点失败！");
				return false;
			}
		}
		return true;
	}

	/**
	 * 审批时生成新的节点
	 * @param tpApproveFlowConfig
	 * @param applyNum
	 * @param date
	 * @param userId
	 * @return
	 * @throws BizException
	 */
	@Override
	public Boolean addNextFlow(TpApproveFlowConfig tpApproveFlowConfig, String applyNum, Date date, Integer userId) {
		String resId = tpApproveFlowConfig.getResId();
		String resIdRc = resId;
		if (resId.contains("[事项录入]")) {
			resId = "[事项录入]";
		}
		LambdaQueryWrapper<TpApproveFlowConfig> flowConfig = new LambdaQueryWrapper<>();
		flowConfig.eq(TpApproveFlowConfig::getResId, resId)
				.eq(tpApproveFlowConfig.getNextFlowNode() != null, TpApproveFlowConfig::getCurrentFlowLink, tpApproveFlowConfig.getNextFlowNode());
		TpApproveFlowConfig nextConfig = tpApproveFlowConfigService.getOne(flowConfig);
		int auditDepartmentId = nextConfig.getAuditDepartmentId();
		int auditRoleId = nextConfig.getAuditRoleId();
		if (resId.contains("[事项录入]")) {
			// 新增下一节点
			TpApproveFlow tpApproveFlowRc = new TpApproveFlow();
			tpApproveFlowRc.setApplyId(applyNum).setApprovalDeptId(auditDepartmentId)
					.setApprovalRoleId(auditRoleId).setResId(resIdRc).setResult(1).setFlowAvailable(1)
					.setCreateTime(date).setCurrentFlowLink(tpApproveFlowConfig.getNextFlowNode()).setUserId(userId);
			boolean save = tpApproveFlowService.save(tpApproveFlowRc);
			if (!save) {
				log.info("新增下一节点失败！");
				return false;
			}
		} else {
			// 新增下一节点
			TpApproveFlow tpApproveFlow = new TpApproveFlow();
			tpApproveFlow.setApplyId(applyNum).setApprovalDeptId(auditDepartmentId)
					.setApprovalRoleId(auditRoleId).setResId(resId).setResult(1).setFlowAvailable(1)
					.setCreateTime(date).setCurrentFlowLink(tpApproveFlowConfig.getNextFlowNode()).setUserId(userId);
			boolean save = tpApproveFlowService.save(tpApproveFlow);
			if (!save) {
				log.info("新增下一节点失败！");
			    return false;
			}
		}
		return true;
	}

	/**
	 * 审批时生成新的节点,不走flowConfig
	 * @param tpApproveFlow
	 * @param applyNum
	 * @param date
	 * @param userId
	 * @return
	 * @throws BizException
	 */
	@Override
	public Boolean addNextFlowNotByConfIg(TpApproveFlow tpApproveFlow,String applyNum, Date date, Integer userId,Integer deptBaseId,Integer roleBaseId) {
		String resId = tpApproveFlow.getResId();
		String resIdRc = resId;
		if (resId.contains("[事项录入]")) {
			resId = "[事项录入]";
		}
		if (resId.contains("[事项录入]")) {
			// 新增下一节点
			TpApproveFlow tpApproveFlowRc = new TpApproveFlow();
			tpApproveFlowRc.setApplyId(applyNum).setApprovalDeptId(deptBaseId)
					.setApprovalRoleId(roleBaseId).setResId(resIdRc).setResult(1).setFlowAvailable(1)
					.setCreateTime(date).setCurrentFlowLink(2).setUserId(userId);
			boolean save = tpApproveFlowService.save(tpApproveFlowRc);
			if (!save) {
				log.info("新增下一节点失败！");
				return false;
			}
		} else {
			// 新增下一节点
			TpApproveFlow tpApproveFlowRc = new TpApproveFlow();
			tpApproveFlowRc.setApplyId(applyNum).setApprovalDeptId(deptBaseId)
					.setApprovalRoleId(roleBaseId).setResId(resId).setResult(1).setFlowAvailable(1)
					.setCreateTime(date).setCurrentFlowLink(2).setUserId(userId);
			boolean save = tpApproveFlowService.save(tpApproveFlowRc);
			if (!save) {
				log.info("新增下一节点失败！");
				return false;
			}
		}
		return true;
	}

	@Override
	public Boolean insertMany(List<TpApproveFlow> list) {
		return tpApproveFlowMapper.saveMany(list);
	}

	@Override
	public Integer selectMaxEdition(String applyId) {
		return tpApproveFlowMapper.getMaxEdition(applyId);
	}

	@Override
	public Boolean addSubNode(String applyId, Integer userId, Integer operType, Date createTime, String resId) {
		TpApproveFlow tpApproveFlow = new TpApproveFlow();
		tpApproveFlow.setApplyId(applyId).setUserId(userId).setOperType(operType)
				.setCreateTime(createTime).setFlowAvailable(1).setResId(resId);
		boolean save = tpApproveFlowService.save(tpApproveFlow);
		return save;
	}

	@Override
	public Boolean addSubNodes(List<AddApprovalsParam> addApprovalsParams, Integer operType, Integer flowAvailable, Date createTime) {
		// userQueryApi.listDeptByIds()  优化，该方法被排序
		Boolean aBoolean = tpApproveFlowMapper.addSubNodes(addApprovalsParams, operType, flowAvailable, createTime);
		return aBoolean;
	}




}
